package mushystuff.dtb.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import mushystuff.dtb.core.model.Sprint;
import mushystuff.dtb.core.service.SprintService;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("sprint")
public class SprintModify extends BaseController {

    @Resource
    protected SprintService sprintService;
    
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }


    @RequestMapping(value = "/sprintModify.do", method = RequestMethod.GET)
    public String selectProduct(
            @RequestParam(value = "sprintId", required = false) Long sprintId,
            ModelMap model, HttpSession session) {
        if (sprintId != null) {
            model.addAttribute("sprint", sprintService.getSprint(sprintId));
        } else {
            model.addAttribute("sprint", new Sprint());
        }
        return "dtb.sprint.modify";
    }

    @RequestMapping(value = "/sprintModify.do", method = RequestMethod.POST)
    public String viewProducts(@ModelAttribute("newSprint") Sprint newSprint,
            SessionStatus status, HttpSession session) {
        productService.addSprint(getCurrentProduct(session), newSprint);
        status.setComplete();
        return "redirect:/productDashboard.do";
    }

}
